/**
 * 描述: 业务逻辑处理 - 单词接口
 * 作者: wz
 * 日期: 2023-12-25
*/
const request = require('request');
const htmlparser2 = require('htmlparser2');

// 获取单词音标
function getWordPronunciation(word) {
	let options = {
	  'method': 'GET',
	  'url': `https://dict.youdao.com/result?word=${encodeURIComponent(word)}&lang=en`,
	  'headers': {
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
		'Cookie': 'OUTFOX_SEARCH_USER_ID=-122041907@10.169.20.65; JSESSIONID=aaaQcZzjNq'
	  }
	}
	return new Promise((resolve, reject) => {
	  request(options, (error, response) => {
		  if (error) { reject(error) }
		  else { 
        //console.log( response.body)
        //resolve(response.body) 
        let phonetic = '';
        let word_zh = '';
        let begin = false;
        let className = '';
        let parser = new htmlparser2.Parser({
          onopentag: function(name, attribs){
            begin = false;
            className = attribs.class;
            if( !begin && name === 'span' && (className === 'phonetic' || className === 'trans')) {
              begin = true;
            }
          },
          ontext: function(text){
            if( begin){
              if( className == 'phonetic' && phonetic.length <= 0){
                phonetic += text;
              }
              if( className == 'trans' && word_zh.length <= 0){
                word_zh += text;
              }
              if( phonetic.length > 0 && word_zh.length > 0){
                resolve({phonetic, word_zh}) 
              }
            }
          },
          onclosetag: function(tagname){
            // if(tagname === 'script') console.log('That\'s it')
          }
        })
        parser.write(response.body);
        parser.end();
        resolve({phonetic, word_zh});
		  }
	  })
	})
}

module.exports = {
  getWordPronunciation
}
